/**
 * Created by plmkz520 on 12/8/15.
 */
angular.module('baisonPromotion', ['baisonDb', 'baisonService'])
        .factory('Promotion', ['$rootScope', '$q', 'dbSelect_rewirte', 'timeStamp2String','dbSelect', function ($rootScope, $q, dbSelect_rewirte, timeStamp2String,dbSelect) {
                //查找与优惠券中promo_id相关联的促销选项
                var getPromotionOptions_by_promo_id = function (id) {
                    var sql = 'select pid,vip_price,customer_price,customer_num,reduce_price,gift_total_price,gift_total_num,rebate,priority from PosPromotionRuleOption where pid="' + id + '"';
                    return dbSelect_rewirte.cx_select('YsPos', sql);
                };
                //查找 查找与优惠券中promo_id相关联的促销主表
                var getPromotionRule_by_promo_id = function (id) {
                    var sql = 'select promotion_rule_id,is_promotion_day_restrict,promotion_day,apply_target,promotion_shop_type,is_region,is_shop,is_coupon,promotion_type,is_share,is_category,is_stop,is_goods,promotion_goods_type,remark,end_time,name,is_use_more from PosPromotionRule where is_audit = "1" and is_stop= "0" and promotion_rule_id="' + id + '"';
                    return dbSelect_rewirte.cx_select('YsPos', sql);
                };
                //获取促销指定商品列表
                var get_goods_by_promotion = function(pid){
                    var goods_sql = 'select rule_goods_id,pid,goods_code,sku from PosPromotionRuleGoods where pid=' + pid;
                    return dbSelect_rewirte.cx_select('YsPos', goods_sql);
                };

                //检查当前可用促销
                var check_current_prom = function (cur_key, list) {
                    //可用
                    var av_prom_keys = Object.keys(list);
                    if (av_prom_keys.indexOf(cur_key.toString()) == -1) {
                        return false;
                    } else {
                        return true;
                    }
                };
                //获取赠品物品
                var get_gift_goods = function (pid) {
                    //rule_gift_id,pid,goods_code,sku,price,goods_name
                    var sql = 'select * from PosPromotionRuleGift where pid ="' + pid + '"';
                    return dbSelect_rewirte.cx_select('YsPos', sql);
                };

                //添加促销
                var add_available_promotion = function (detail) {

                    var _exists = false;
                    $.each($rootScope.goods_cart.available_promotions, function (i, n) {
                        if (detail['promotion_rule_id'] == n['promotion_rule_id']) {
                            _exists = true;
                        }
                    });
                    //不存在
                    if (!_exists) {

                        $rootScope.goods_cart.available_promotions.push(detail);
                    }
                };
                //获取主表促销信息
                var get_main_pro = function(_time){
                     var sql = 'select * from PosPromotionRule where is_audit =1 and is_stop= 0  and begin_time <= "' + _time + '" and end_time >= "' + _time + '"';
                     return dbSelect_rewirte.cx_select('YsPos', sql);
                };
				
                //获取区域促销信息
                var get_region_pro = function(n,_region_code){
                    var region_sql = 'select rule_region_id from PosPromotionRuleRegion where pid = "' + n.promotion_rule_id + '" and region_code="' + _region_code + '"';
                    return dbSelect_rewirte.cx_select('YsPos', region_sql);        
                };
                //获取商店促销信息
                var get_shop_pro = function(n,_shop_code){
                    var shop_sql = 'select rule_shop_id from PosPromotionRuleShop where pid = "' + n.promotion_rule_id + '" and shop_code="' + _shop_code + '"';
                    return dbSelect_rewirte.cx_select('YsPos', shop_sql);             
                };
				//获取同享促销关联信息
				var get_relation_pro = function(n){
					var sql = 'select * from PosPromotionRuleRelation where pid = "'+n.promotion_rule_id+'"';
					return dbSelect_rewirte.cx_select('YsPos', sql);
				};
				//获取同享促销关联信息
				var get_vip_pro = function(n){
					var sql = 'select * from PosPromotionRuleVip where pid = "'+n.promotion_rule_id+'"';
					return dbSelect_rewirte.cx_select('YsPos', sql);
				};
				//获取同享促销关联信息
				var get_viplevel_pro = function(n){
					var sql = 'select * from PosPromotionRuleVipLevel where pid = "'+n.promotion_rule_id+'"';
					return dbSelect_rewirte.cx_select('YsPos', sql);
				};
                //获取今日可用促销
                var get_today_promotion = function () {
                    $rootScope.goods_cart.today_promotions = {};
                    var _time = timeStamp2String(0, 'datetime');
                    var _day = timeStamp2String(0, 'day');
                    var _shop_code = $rootScope.current_shop.ShopCode;
                    var shop_list = [];
                    var shop_deferred = $q.defer();
                    var shop_promise = shop_deferred.promise;
					var n = {};
					var sql = '';
                    return get_main_pro(_time).then(function (ret) {
                        var arr_deferred = {};
                        var arr_promise = {};
                        var execPromotion = function(i){
                            n = ret[i];
                            if(!n){
                                arr_deferred[i].resolve('false');
                                return;
                            }
                            get_shop_pro(n,_shop_code).then(function (shop_ret) {
								shop_list = shop_ret;
								shop_deferred.resolve('true');
								return shop_promise;
                            }).then(function () {
                                
                                 if (n.is_promotion_day_restrict == 1) {
                                     if (n.promotion_day.indexOf(_day) == -1) {
                                         arr_deferred[i].resolve('false');
                                         i++;
                                         execPromotion(i);
                                         return;
                                     }
                                }
                                if (n.promotion_shop_type == 1) {
                                    if (n.is_region == 1) {
                                        if (shop_list.length == 0) {
                                            arr_deferred[i].resolve('false');
                                            i++;
                                            execPromotion(i);
                                            return;
                                        }
                                    }
                                    //店铺正选
                                    if (n.is_shop == 1) {
                                        if (shop_list.length == 0) {
                                            arr_deferred[i].resolve('false');
                                            i++;
                                            execPromotion(i);
                                            return;
                                        }
                                    }

                                    if (n.is_shop == 2) {
                                        if (shop_list.length > 0) {
                                            arr_deferred[i].resolve('false');
                                            i++;
                                            execPromotion(i);
                                            return;
                                        }
                                    }
                                }
								//获取其他节点的信息
								var get_other_node_data = function(n){
									var other_promise = [];
									other_promise['relation'] =get_relation_pro(n).then(function(relation){
										n.relation = relation.length > 0 ?relation:[];
										return $q.when();
									});
									other_promise['vip'] =get_vip_pro(n).then(function(vip){
										n.vip = vip.length > 0?vip:[];
										return $q.when();
									});
									other_promise['viplevel'] =get_viplevel_pro(n).then(function(viplevel){
										n.viplevel = viplevel.length > 0?viplevel:[];
										return $q.when();
									});
									
									return $q.all(other_promise);
								};
								get_other_node_data(n).then(function(){
									$rootScope.goods_cart.today_promotions[n.promotion_rule_id] = n;
									arr_deferred[i].resolve('true');
									i++;
									execPromotion(i);
									return;
								});
                                
                            });
                        };
                        //设置版本配置项
                        for (var j = 0; j <= ret.length; j++) {
                            arr_deferred[j] = $q.defer();
                            arr_promise[j] = arr_deferred[j].promise;
                        }

                        var index = 0;
                        execPromotion(index);
                        return $q.all(arr_promise);
                    });
                };
                
                //获取促销里是否有可以的促销规则(满钱)(不叠加)
                var get_promotion_options_money = function(promotion,_money){
                	var n = {};
                	var option_info = {};
                	option_info.money = 0;
                	option_info.index = -1;
                    option_info.can_used_num = 0;
                    if(promotion.options){

                    
					for(var i = 0;i < promotion.options.length;i++){
						n = promotion.options[i];
						if (_money >= n.customer_price){
							if(n.customer_price > option_info.money){
								option_info.money = n.customer_price;
								option_info.index = i;
							}else if(n.customer_price == option_info.money){
                                option_info.money = n.customer_price;
								option_info.index = i;
								if(n.priority < promotion.options[option_info.index].priority){
									option_info.money = n.customer_price;
									option_info.index = i;
								}
							}
                        }
					}
                    //促销条件满足
                    if(option_info.index != -1){
                        option_info.can_used_num = option_info.money >0 ?parseInt(_money/option_info.money):1;
                    }
                    //获取优惠券使用个数
                    if(promotion.is_coupon && $rootScope.goods_cart.couponData[promotion.promotion_rule_id] != undefined){
                        var coupon_num = $rootScope.goods_cart.couponData[promotion.promotion_rule_id].coupon.coupon_code.length;
                        if(option_info.money <= 0){
                            option_info.can_used_num = coupon_num;
                        }else{
                            option_info.can_used_num = (option_info.can_used_num > coupon_num)?coupon_num:option_info.can_used_num;
                        }
                        
                    }
                    promotion.is_use_more = promotion.is_use_more==undefined?0:promotion.is_use_more;
                    //促销叠加开关
                    if(promotion.is_use_more==0 && option_info.index != -1){
                        option_info.can_used_num = 1;
                    }
					if(option_info.can_used_num > 1 && promotion.is_use_more > 0 && option_info.index != -1){
						option_info.can_used_num = option_info.can_used_num > promotion.is_use_more?promotion.is_use_more:option_info.can_used_num;
					}
                    }
					return option_info;
                };
                //获取促销里是否有可以的促销规则(满件)(不叠加)
                var get_promotion_options_num = function(promotion,_num){
                	var n = {};
                	var option_info = {};
                	option_info.num = 0;
                	option_info.index = -1;
                    option_info.can_used_num = 0;
                    if(promotion.options){
					for(var i = 0;i < promotion.options.length;i++){
						n = promotion.options[i];
						if (_num >= n.customer_num){
							if(n.customer_num > option_info.num){
								option_info.num = n.customer_num;
								option_info.index = i;
							}else if(n.customer_num == option_info.num){
                                option_info.num = n.customer_num;
								option_info.index = i;
								if(n.priority < promotion.options[option_info.index].priority){
									option_info.num = n.customer_num;
									option_info.index = i;
								}
							}
                        }
					}
                     //促销条件满足
                    if(option_info.index != -1){
                        option_info.can_used_num = option_info.num > 0?parseInt(_num/option_info.num):1;
                    }
                    //获取优惠券使用个数
                    if(promotion.is_coupon && $rootScope.goods_cart.couponData[promotion.promotion_rule_id] != undefined){
                        var coupon_num = $rootScope.goods_cart.couponData[promotion.promotion_rule_id].coupon.coupon_code.length;
                        
                        if(option_info.num <= 0){
                            option_info.can_used_num = coupon_num;
                        }else{
                            option_info.can_used_num = (option_info.can_used_num > coupon_num)?coupon_num:option_info.can_used_num;
                        }
                        
                    }
                    
                    promotion.is_use_more = promotion.is_use_more==undefined?0:promotion.is_use_more;
                    //促销叠加开关
                    if(promotion.is_use_more==0 && option_info.index != -1){
                        option_info.can_used_num = 1;
                    }
					if(option_info.can_used_num > 1 && promotion.is_use_more > 0 && option_info.index != -1){
						option_info.can_used_num = option_info.can_used_num > promotion.is_use_more?promotion.is_use_more:option_info.can_used_num;
					}
                    }
					return option_info;
                };
                //获取可用促销逻辑
                var get_available_promotion_by_list = function (n, isUse, goods_sku_list_key) {
                    
                    var _money = 0; //总金额
                    var _num = 0; //数量
                    var index = -1; 
                    var _promotion_goods = [];
                    var option_info = {};
                	option_info.money = 0;
                    option_info.num = 0;
                	option_info.index = -1;
                    option_info.can_used_num = 0;
                    //指定范围商品
                    if (n.promotion_goods_type == 1) {
                        ////循环购物车里面的
                        $.each($rootScope.goods_cart.list, function (key, val) {
                            var index = goods_sku_list_key.indexOf(val.SkuCode);//$.inArray(val.SkuCode, goods_sku_list_key);
                            if (index != -1 ) { //&& val.promotionid == undefined
                                switch (parseInt(n.promotion_type)) {
                                    case 0: //满额立减
									case 7:
                                    case 1: //满额赠件
                                    case 4: //满额打折
									case 9:
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //获取使用的优惠券
                                            $.each($rootScope.goods_cart.couponData, function (i, v) {
                                                if (v.coupon.promo_id == n.promotion_rule_id) {
                                                    _money = _money + parseFloat(val.money);
                                                }
                                            });
                                        } else {
                                            _money = _money + parseFloat(val.money);
                                        }

                                        break;
                                    case 2: //满件减钱
                                    case 3: //满件赠件
									case 8:
										if (n.is_coupon == 1) {//是绑定优惠券的
											//TODO 获取使用的优惠券
											$.each($rootScope.goods_cart.couponData, function (i, v) {

												if (v.coupon.promo_id == n.promotion_rule_id) {
													var num = val.num >val.goods_num?val.num:val.goods_num;
													_num = _num + parseFloat(num);
												}
											});
										} else {
											
											var num = val.num >val.goods_num?val.num:val.goods_num;
													_num = _num + parseFloat(num);
										}
                                        break;
                                    case 5:
									case 10:
										
                                        //套组
                                        break;
                                    case 6:
                                        //积分
                                        break;
                                }
                            }
                        });
                        switch (parseInt(n.promotion_type)) {
                            case 0: //满额立减
                            case 1: //满额赠件
                            case 4: //满额打折 
							case 7:
							case 9:
								option_info = get_promotion_options_money(n,_money);
                                break;
                            case 2: //满件减钱
                            case 3: //满件赠件
							case 8:
								option_info = get_promotion_options_num(n,_num);
                                break;
                            case 5:
							case 10:
                                //套组
                                option_info.index = 0;
                                option_info.can_used_num = 1;
                                break;
                            case 6:
                                //积分
                                break;
                        }
                    } else {
                        //促销策略中没有指定商品
                        $.each($rootScope.goods_cart.list, function (key, val) {
                            //if (val.promotionid == undefined) {
                                switch (parseInt(n.promotion_type)) {
                                    case 0: //满额立减
                                    case 1: //满额赠件
                                    case 4: //满额打折 
									case 7:
									case 9:
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //获取使用的优惠券
                                            $.each($rootScope.goods_cart.couponData, function (i, v) {
                                                if (v.coupon.promo_id == n.promotion_rule_id) {
                                                    _money = _money + parseFloat(val.money);
                                                }
                                            });
                                        } else {
                                            _money = _money + parseFloat(val.money);
                                        }
                                        break;
                                    case 2: //满件减钱
                                    case 3: //满件赠件 
									case 8:
									
                                        if (n.is_coupon == 1) {//是绑定优惠券的
                                            //TODO 获取使用的优惠券

                                            $.each($rootScope.goods_cart.couponData, function (i, v) {
                                                if (v.coupon.promo_id == n.promotion_rule_id) {
                                                   var num = val.num >val.goods_num?val.num:val.goods_num;
													_num = _num + parseFloat(num);
                                                }
                                            });
                                        } else {
											
                                            var num = val.num >val.goods_num?val.num:val.goods_num;
													_num = _num + parseFloat(num);
                                        }

                                        break;
                                    case 5:
									case 10:
                                        //套组
                                        break;
                                    case 6:
                                        //积分
                                        break;
                                }
                        });
                        switch (parseInt(n.promotion_type)) {
                            case 0: //满额立减
                            case 1: //满额赠件
                            case 4: //满额打折
                            case 7:
                            case 9:
                                _money = $rootScope.goods_cart.info.need_money;
                                break;
                        }

                        switch (parseInt(n.promotion_type)) {
                            case 0: //满额立减
                            case 1: //满额赠件
                            case 4: //满额打折 
							case 7:
							case 9:
								option_info = get_promotion_options_money(n,_money);
                                break;
                            case 2: //满件减钱
                            case 3: //满件赠件 
							case 8:
								option_info = get_promotion_options_num(n,_num);
                                break;
                            case 5:
							case 10:
                                //套组
                                option_info.index = 0;
                                option_info.can_used_num = 1;
                                break;
                            case 6:
                                //积分
                                break;
                        }
                    }
                    
                    return option_info;
                };

                //获取促销分类信息
                var get_category_pro = function(n){
                    var category_sql = 'select rule_category_id,pid,category_id,category_code from PosPromotionRuleCategory where pid=' + n.promotion_rule_id;
                    return dbSelect_rewirte.cx_select('YsPos', category_sql);
                };
                //获取促销条件信息
                var get_option_pro = function(n){
                    var option_sql = 'select pid,vip_price,customer_price,customer_num,reduce_price,gift_total_price,gift_total_num,rebate,priority  from PosPromotionRuleOption where pid = ' + n.promotion_rule_id;
                    return dbSelect_rewirte.cx_select('YsPos', option_sql);         
                };
                //获取促销商品信息
                var get_goods_pro = function(n){
                    var goods_sql = 'select rule_goods_id,pid,goods_code,sku,price from PosPromotionRuleGoods where pid=' + n.promotion_rule_id;
                    return dbSelect_rewirte.cx_select('YsPos', goods_sql);              
                };
                //计算可用促销
                var calculate_available_promotion  = function(){
                    return get_today_promotion().then(function (ret) {
                        if (Object.keys($rootScope.goods_cart.today_promotions).length == 0) {
                            return;
                        }
                        $rootScope.goods_cart.available_promotions = {};
                        $rootScope.goods_cart.promotion_goods = {};

                        var promiseAll = [];
                        var option_list = [];
                        var category_list = [];
                        var goods_list = [];
                        var goods_sku_list_key = [];
                        var isUse = false;//是否成功使用促销
                        var index = -1;
                        var _promotion_goods = [];//促销商品

                        var cate_deferred = $q.defer();
                        var cate_promise = cate_deferred.promise; //分类
                        var good_deferred = $q.defer();
                        var good_promise = good_deferred.promise;
                        var _promotion = {};
                        var key_arr = Object.keys($rootScope.goods_cart.today_promotions);
                        var arr_deferred = {};
                        var arr_promise = {};
                        var execPromotion = function(i){
                            n = $rootScope.goods_cart.today_promotions[key_arr[i]];
                            if(!n){
                                arr_deferred[i].resolve('false');
                                return;
                            }
                            get_option_pro(n).then(function (option_ret) {
                                option_list = option_ret;
                                return get_category_pro(n).then(function (category_ret) {
                                    category_list = category_ret;
                                    cate_deferred.resolve('true');
                                    return cate_promise;
                                })
                            }).then(function (ret) {
                                return get_goods_pro(n).then(function (goods_ret) {
									goods_sku_list_key = [];
                                    $.each(goods_ret, function (_g_k, _g_v) {
                                        goods_sku_list_key.push(_g_v.sku);
                                    });
                                    n.goodslist = goods_list = goods_ret;
                                    n.goods_list = goods_sku_list_key;
                                    good_deferred.resolve('true');
                                    return good_promise;
                                })
                            }).then(function (ret) {
                                /*
                                //选择促销内已有独享的，不能重复选择独享
                                if ($rootScope.goods_cart.share_promotion_id > 0) {
                                    if (n.is_share == 0 && $rootScope.goods_cart.share_promotion_id != n.promotion_rule_id) {
                                        arr_deferred[i].resolve('false');
                                        i++;
                                        execPromotion(i);
                                        return;
                                    }
                                }
                                */
                                _promotion = n;
                                n.goods_list = goods_sku_list_key;
                                _promotion.options = option_list;
                                _promotion.goods_list = goods_sku_list_key;
                                $rootScope.goods_cart.available_promotions[n.promotion_rule_id] = _promotion;
                                arr_deferred[i].resolve('true');
                                i++;
                                execPromotion(i);
                                return;
                            });
                        };


                        

                        //设置版本配置项
                        for (var j = 0; j <= key_arr.length; j++) {
                            arr_deferred[j] = $q.defer();
                            arr_promise[j] = arr_deferred[j].promise;
                        }

                        var index = 0;
                        execPromotion(index);
                        return $q.all(arr_promise);
                    });
                };
                //可用促销处理
                var available_promotions_detail = function(n,isUse){
                    var _promotion = n;
                    var goods_sku_list_key = n.goods_list;
                    var option_list = n.options;
                    var option_info = get_available_promotion_by_list(_promotion, isUse, goods_sku_list_key);
                    if(option_info.index != -1 && option_info.index != undefined){
                        _promotion.reduce_price = option_list[option_info.index].reduce_price;
                        _promotion.gift_total_price = option_list[option_info.index].gift_total_price;
                        _promotion.gift_total_num = option_list[option_info.index].gift_total_num;
                        _promotion.rebate = option_list[option_info.index].rebate;
                        _promotion.customer_price = option_list[option_info.index].customer_price;
                        _promotion.customer_num = option_list[option_info.index].customer_num;
                        _promotion.vip_price = option_list[option_info.index].vip_price;
                        _promotion.goods_list = goods_sku_list_key;
                        _promotion.can_used_num = option_info.can_used_num;
                        isUse = true;
                    }
                    if (isUse) {
                        $rootScope.goods_cart.available_promotions[n.promotion_rule_id] = _promotion;
                        return true;
                    }else{
                        delete $rootScope.goods_cart.available_promotions[n.promotion_rule_id];
                        return false;
                    }
                };
                //获取可用促销逻辑
                var get_available_promotion_logic = function(){
                    $rootScope.goods_cart.available_promotions = {};
                    $rootScope.goods_cart.promotion_goods = {};
                    var promiseAll = [];
                    var option_info = {};
                    var _promotion = {};
                    var isUse = false;
                    var goods_sku_list_key = [];
                    var option_list = [];
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    $.each($rootScope.goods_cart.today_promotions, function (i, n) {
                        available_promotions_detail(n,isUse);
                    });
                    deferred.resolve('true');
                    return promise;
                };

                //获取可用促销
                var get_available_promotion = function () {
                    if(!$rootScope.goods_cart.is_ready_take){
                        baison_app.api.showProgress({
                            title: "请稍等",
                            text: '',
                            modal: false
                        });
                        return calculate_available_promotion().then(function(ret){
                            baison_app.api.hideProgress();
                            $rootScope.goods_cart.is_ready_take = true;
                            return get_available_promotion_logic();
                        }); 
                    }else{
                        return get_available_promotion_logic();
                    }
                    
                
                };
                var list = function () {
                    return calculate_available_promotion();
                };
                var tactic_integral_withdrawals = function(){
                    var sql1 = 'select * from tactic_integral_withdrawals order by integral_withdrawals_id desc limit 1';
                    return $q.all({
                        'jf_unit': dbSelect('YsPos', sql1)
                    });
				};
				
                return {
                    list: list,
                    check_current_prom: check_current_prom,
                    get_gift_goods: get_gift_goods,
                    get_today_promotion: get_today_promotion,
                    get_available_promotion: get_available_promotion,
                    getPromotionOptions_by_promo_id: getPromotionOptions_by_promo_id,
                    getPromotionRule_by_promo_id: getPromotionRule_by_promo_id,
                    get_goods_by_promotion:get_goods_by_promotion,
                    calculate_available_promotion:calculate_available_promotion,
                    available_promotions_detail:available_promotions_detail,
					tactic_integral_withdrawals:tactic_integral_withdrawals
                };
            }]);